<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Session;
use app\model\MyRedis;
use app\traits\MyModelTrait;
use app\model\AdminUser;

/**
 * admin_user 登录态校验
 *
 * Class AdminUserTokenMiddleware
 * @package app\middleware
 */
class AdminUserTokenMiddleware
{
    use MyModelTrait;
    
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token/s', '');
        $redis = MyRedis::generateRedisInstance();
        if (strlen($token) > 30)
        {
            $token_key   = 'admin_user.'.self::generateTokenKey($token);
            $redis_token = $redis->get($token_key);
            if ($token !== $redis_token) return redirect('/admin/user/login', 302);
        } else {
            $token_key   = AdminUser::getTokenKey((int)session('admin_user.id'));
            $redis_token = $redis->get($token_key);
            if (
                session('admin_user.id') === false ||
                Session::has($token_key) === false ||
                $redis_token !== Session::get($token_key)
            ) return redirect('/admin/user/login', 302);
        }

        return $next($request);
    }
}
